package net.dgg.zz.credential.storageCapacity.service;

import net.dgg.framework.tac.utils.idutil.DggKeyWorker;
import net.dgg.iboss.base.service.CmsService;
import net.dgg.tmd.foundation.platform.common.util.TranslateUtil;
import net.dgg.tmd.foundation.platform.session.SessionManager;
import net.dgg.tmd.foundation.platform.user.entity.UserEntity;
import net.dgg.zz.common.base.service.BaseService;
import net.dgg.zz.common.excption.CommonExcption;
import net.dgg.zz.common.service.CommonService;
import net.dgg.zz.common.systemRecord.entity.SystemRecord;
import net.dgg.zz.common.systemRecord.service.SystemRecordService;
import net.dgg.zz.common.utils.StringUtils;
import net.dgg.zz.common.utils.ValidateUtils;
import net.dgg.zz.credential.excption.CertificateExcption;
import net.dgg.zz.credential.storageCapacity.dao.StorageCapacityDao;
import net.dgg.zz.credential.storageCapacity.entity.StorageCapacity;
import net.dgg.zz.credential.storageCapacity.entity.StorageCapacityVo;
import org.apache.commons.beanutils.ConvertUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class StorageCapacityService extends BaseService {

    @Autowired
    private StorageCapacityDao storageCapacityDao;

    @Autowired
    private SessionManager sessionManager;

    @Autowired
    private SystemRecordService systemRecordService;

    @Autowired
    private CmsService cmsService;

    @Autowired
    private CommonService commonService;
    @Autowired
    private TranslateUtil translateUtil;

    public int insert(StorageCapacity record) {
        return storageCapacityDao.insert(record);
    }

    public int update(StorageCapacity record) {
        return storageCapacityDao.updateByPrimaryKeySelective(record);
    }

    public List<StorageCapacity> findByCondition(Map params) {
        return storageCapacityDao.findByCondition(params);
    }

    public String storageCapacityCode = "";
    public Long storageCapacityId = null;

    /**
     * 判断证书基本类型是否存在  不存在则添加
     *
     * @param params
     */
    @Transactional
    public List<StorageCapacity> verificationStorageCapacity(Map params) {

        // certificateSpecialty为证书专业或者资质名称的数组
        ValidateUtils.isTrue(params.containsKey("certificateSpecialty"), CertificateExcption.class, "证书专业不能为空");
        ValidateUtils.isTrue(params.containsKey("certificateTypeId"), CertificateExcption.class, "证书类型不能为空");
        ValidateUtils.isTrue(params.containsKey("certificateLevel"), CertificateExcption.class, "证书等级不能为空");
        ValidateUtils.isTrue(params.containsKey("certificateArea"), CertificateExcption.class, "证书地区不能为空");
        ValidateUtils.isTrue(params.containsKey("applicationScope"), CertificateExcption.class, "证书适用范围不能为空");
        ValidateUtils.isTrue(params.containsKey("generalType"), CertificateExcption.class, "证书种类不能为空");
        ValidateUtils.isTrue(params.containsKey("signOrgId"), CertificateExcption.class, "证书所属事业部不能为空");

        // 证书专业数组
        String certificateSpecialties = params.containsKey("certificateSpecialty") ? params.get("certificateSpecialty").toString() : null;
        Long[] certificateSpecialtys = (Long[]) ConvertUtils.convert(certificateSpecialties.split(","), Long.class);


        UserEntity user = sessionManager.getCurrentUser();
        StorageCapacity storageCapacity = null;
        for (Long certificateSpecialty : certificateSpecialtys) {
            params.put("certificateMajor", certificateSpecialty);

            // 判断当前证书专业以及其他条件是否已经存在在基本类型中
            storageCapacity = storageCapacityDao.findStorageCapacity(params);
            storageCapacityCode = params.get("generalType").toString() + certificateSpecialty + params.get("certificateArea").toString() + params.get("signOrgId").toString() + params.get("certificateLevel").toString() + params.get("certificateTypeId").toString() + params.get("applicationScope").toString();
            synchronized (storageCapacityCode) {
                if (StringUtils.isEmpty(storageCapacity)) { // 不存在的基本类型
                    storageCapacity = new StorageCapacity();
                    storageCapacity.setId(DggKeyWorker.nextId());
                    storageCapacity.setCreateUser(user);
                    storageCapacity.setCertificateArea(params.containsKey("certificateArea") && StringUtils.isNotEmpty(params.get("certificateArea")) ? params.get("certificateArea").toString() : null);
                    storageCapacity.setSignOrgId(params.containsKey("signOrgId") && StringUtils.isNotEmpty(params.get("signOrgId")) ? Long.parseLong(params.get("signOrgId").toString()) : null);
                    storageCapacity.setCertificateLevel(params.containsKey("certificateLevel") && StringUtils.isNotEmpty(params.get("certificateLevel")) ? params.get("certificateLevel").toString() : null);
                    storageCapacity.setCertificateMajorId(certificateSpecialty);
                    storageCapacity.setCertificateTypeId(params.containsKey("certificateTypeId") && StringUtils.isNotEmpty(params.get("certificateTypeId")) ? Long.parseLong(params.get("certificateTypeId").toString()) : null);
                    storageCapacity.setApplicationScope(params.containsKey("applicationScope") && StringUtils.isNotEmpty(params.get("applicationScope")) ? params.get("applicationScope").toString() : null);
                    Map serviceOrg = cmsService.findOrg(Long.valueOf(params.get("signOrgId").toString()));
                    ValidateUtils.strNotEmpty(serviceOrg, CertificateExcption.class, "所属事业部为空,请联系管理员!");
                    storageCapacity.setSignOrgName(serviceOrg.get("name").toString());

                    String number = cmsService.getBillNumber("CT");
                    ValidateUtils.isTrue(StringUtils.isNotEmpty(number), CommonExcption.class, "单据号获取失败,请联系管理员");

                    storageCapacity.setCertificateCode(number);
                    storageCapacity.setGeneralType(params.containsKey("generalType") && StringUtils.isNotEmpty(params.get("generalType")) ? params.get("generalType").toString() : null);
                    storageCapacity.setStatus(0);
                    storageCapacity.setProvinceArea(commonService.translateCityCode(storageCapacity.getCertificateArea()));
                    storageCapacityDao.insert(storageCapacity);

                    // 保存操作日志
                    SystemRecord systemRecord = new SystemRecord();
                    systemRecord.setSource("1");
                    systemRecord.setOperateType("1");
                    systemRecord.setWorkTableName("zz_storage_capacity");
                    systemRecord.setWorkId(storageCapacity.getId());
                    systemRecord.setWorkNo(storageCapacity.getCertificateCode());
                    systemRecord.setSignOrgId(storageCapacity.getSignOrgId());
                    systemRecord.setSignOrgName(storageCapacity.getSignOrgName());
                    systemRecord.setRemarks("证书中心：新增证书基本类型");
                    systemRecordService.save(systemRecord);
                }
            }
        }
        params.put("certificateSpecialtys", certificateSpecialtys);
        List<StorageCapacity> allList = storageCapacityDao.findStorageCapacitys(params);
        return allList;
    }

    /**
     * 修改库容量
     *
     * @param storageCapacitys 证书基本类型List
     */
    @Transactional
    public void updateStorageCapacityCount(List<StorageCapacity> storageCapacitys) {
        UserEntity user = sessionManager.getCurrentUser();
        if (storageCapacitys != null && !storageCapacitys.isEmpty()) {
            for (StorageCapacity s : storageCapacitys) {
                Map params = new HashMap();
                params.put("sId", s.getId());
                StorageCapacity storageCapacity = storageCapacityDao.findStorageCapacity(params);
                storageCapacityId = storageCapacity.getId();
                synchronized (storageCapacityId) {
                    // 修改库容量
                    storageCapacity.setLibraryNumbers(s.getLibraryNumbers());
                    storageCapacity.setReserveNumbers(s.getReserveNumbers());
                    storageCapacity.setHangUpNumbers(s.getHangUpNumbers());
                    storageCapacity.setOrderNumbers(s.getOrderNumbers());
                    storageCapacity.setMatchNumbers(s.getMatchNumbers());
                    storageCapacity.setUpdaterUser(user);

                    storageCapacityDao.updateByPrimaryKey(storageCapacity);
                    // 保存操作日志
                    SystemRecord systemRecord = new SystemRecord();
                    systemRecord.setSource("1");
                    systemRecord.setOperateType("2");
                    systemRecord.setWorkTableName("zz_storage_capacity");
                    systemRecord.setWorkId(storageCapacity.getId());
                    systemRecord.setWorkNo(storageCapacity.getCertificateCode());
                    systemRecord.setRemarks("证书中心：修改证书统计数量");
                    systemRecordService.save(systemRecord);
                }

            }
        }
    }

    /**
     * 根据证书id查询证书绑定的基本类型
     *
     * @param id
     * @return
     */
    public List<StorageCapacity> findStorageCapacityByCertificateId(Long id) {
        return storageCapacityDao.findStorageCapacityByCertificateId(id);
    }

    /**
     * 根据证书基本类型code查询证书基本类型信息
     *
     * @param id
     * @return
     */
    public List<StorageCapacity> findStorageCapacitysByCodes(List<String> certificateSpecialtyCodes) {
        return storageCapacityDao.findStorageCapacitysByCodes(certificateSpecialtyCodes);
    }

    /**
     * 分页查询证书基本信息
     *
     * @param params
     * @return
     */
    public List<StorageCapacityVo> queryStorageCapacityWithPage(Map params) {
        if (params.containsKey("isAll") && params.get("isAll").equals("0")) {
            params.put("signOrgId", commonService.findUserSyb(sessionManager.getCurrentUser()));
        }
        if (null == params.get("orderColumn")) {
            params.put("orderDir", "desc");//排序方向
            params.put("orderColumn", "zsc.sign_org_id,zct.certificate_name,pzct.certificate_name");//排序的列
        }
        List<StorageCapacityVo> storageCapacities = storageCapacityDao.queryStorageCapacityWithPage(params);
        String[] column = {"certificateArea", "applicationScope", "certificateLevel"};
        storageCapacities = translateUtil.translateList(column, storageCapacities);
        return storageCapacities;
    }

    /**
     * 证书总览：证书库容
     *
     * @param params
     * @return
     */
    public List<Map> generalCredentialWarningCount(Map params) {
        if (params.containsKey("isAll") && params.get("isAll").equals("0")) {
            params.put("signOrgId", commonService.findUserSyb(sessionManager.getCurrentUser()));
        }
        return storageCapacityDao.generalCredentialWarningCount(params);
    }

    /**
     * 查询所有的证书基本类型数据
     *
     * @param params
     * @return
     */
    public List<StorageCapacity> findStorageCapacitys(Map params) {
        ValidateUtils.isTrue(params.containsKey("certificateSpecialty"), CertificateExcption.class, "证书专业不能为空");
        ValidateUtils.isTrue(params.containsKey("certificateTypeId"), CertificateExcption.class, "证书类型不能为空");
        ValidateUtils.isTrue(params.containsKey("certificateLevel"), CertificateExcption.class, "证书等级不能为空");
        ValidateUtils.isTrue(params.containsKey("certificateArea"), CertificateExcption.class, "证书地区不能为空");
        ValidateUtils.isTrue(params.containsKey("applicationScope"), CertificateExcption.class, "证书适用范围不能为空");
        ValidateUtils.isTrue(params.containsKey("generalType"), CertificateExcption.class, "证书种类不能为空");
        ValidateUtils.isTrue(params.containsKey("signOrgId"), CertificateExcption.class, "证书所属事业部不能为空");
        String certificateSpecialties = params.containsKey("certificateSpecialty") ? params.get("certificateSpecialty").toString() : null;
        Long[] certificateSpecialtys = (Long[]) ConvertUtils.convert(certificateSpecialties.split(","), Long.class);
        params.put("certificateSpecialtys", certificateSpecialtys);
        return storageCapacityDao.findStorageCapacitys(params);
    }

    /**
     * 根据证书类型统计证书库容，不再统计专业个数。统计落实到实实在在的证书个数
     * @param params
     * @return
     */
    public List<Map> generalCredentialWarningCountByType(Map params) {
        if (params.containsKey("isAll") && params.get("isAll").equals("0")) {
            params.put("signOrgId", commonService.findUserSyb(sessionManager.getCurrentUser()));
        }
        return storageCapacityDao.generalCredentialWarningCountByType(params);
    }

    /**
     * 根据证书类型统计证书库容
     * @param params
     * @return
     */
    public List<Map> queryStorageCapacityByTypeWithPage(Map params) {
        if (params.containsKey("isAll") && params.get("isAll").equals("0")) {
            params.put("signOrgId", commonService.findUserSyb(sessionManager.getCurrentUser()));
        }
        if (null == params.get("orderColumn")) {
            params.put("orderDir", "desc");//排序方向
            params.put("orderColumn", "s.sign_org_id,t.certificate_name");//排序的列
        }
        List<Map> storageCapacities = storageCapacityDao.queryStorageCapacityByTypeWithPage(params);
        String[] column = {"certificateArea", "applicationScope", "certificateLevel"};
        storageCapacities = translateUtil.translateList(column, storageCapacities);
        return storageCapacities;
    }
}
